// pages/chat/chat.js
const app = getApp();

Page({
  data: {
    inputText: "",
    messages: []
  },
  onInput(e) {
    this.setData({
      inputText: e.detail.value
    });
  },
  onSend() {
    const { inputText } = this.data;
    if (!inputText.trim()) return;

    // 使用全局Worker实例
    const worker = app.globalData.worker;

    worker.postMessage(inputText);

    worker.onMessage((res) => {
      const responseMessage = res;
      this.appendMessage({ text: responseMessage, type: "customer" });
    });

    worker.onError((e) => {
      console.error('Worker error:', e.message);
    });

    // 清空输入框并添加用户消息
    this.setData({ inputText: "" });
    this.appendMessage({ text: inputText, type: "user" });
  },
  appendMessage(message) {
    this.setData({
      messages: [...this.data.messages, message]
    });
    wx.setStorageSync('chat_history', this.data.messages);  // 保存历史记录
  },
  onNavigateToHistory() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },
  onLoad() {
    this.loadHistory();
  },
  loadHistory() {
    const history = wx.getStorageSync('chat_history') || [];
    this.setData({
      messages: history
    });
  }
});